package com.example.remote;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

public class Server {
    private static Map<String, InetSocketAddress> clientAddresses = new HashMap<>();
    private static final int SERVER_PORT = 12345;

    public static void main(String[] args) {
        try {
            DatagramSocket socket = new DatagramSocket(SERVER_PORT);
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            System.out.println("server listener on: " + SERVER_PORT);
            while (true) {
                socket.receive(packet);
                String message = new String(packet.getData(), 0, packet.getLength());
                if (message.startsWith("REGISTER")) {
                    String clientId = message.split(":")[1];
                    InetSocketAddress clientSocketAddress = new InetSocketAddress(packet.getAddress(), packet.getPort());
                    clientAddresses.put(clientId, clientSocketAddress);
                    System.out.println("Registered client: " + clientId + " with address: " + clientSocketAddress);
                } else if (message.startsWith("GET_CLIENT")) {
                    String clientId = message.split(":")[1];
                    InetSocketAddress targetAddress = clientAddresses.get(clientId);
                    if (targetAddress!= null) {
                        String hostAddress = targetAddress.getAddress().getHostAddress() + ":" +  targetAddress.getPort();
                        byte[] response = hostAddress.getBytes();
                        DatagramPacket responsePacket = new DatagramPacket(response, response.length, packet.getAddress(), packet.getPort());
                        socket.send(responsePacket);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
